package com.linkage.jz.bankruptcy.activity.Project.ZQUser;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.adapter.FullyGridLayoutManager;
import com.linkage.jz.bankruptcy.base.BaseCreateActivity;
import com.linkage.jz.bankruptcy.bean.ObjValInfo;
import com.linkage.jz.bankruptcy.bean.SerializedZQApplyFileList;
import com.linkage.jz.bankruptcy.bean.TaskAtta;
import com.linkage.jz.bankruptcy.bean.ZQBaseProjectCrDecInfo;
import com.linkage.jz.bankruptcy.utils.SelectPicHelpler;
import com.linkage.jz.bankruptcy.utils.UploadImageConverter;
import com.linkage.seapeak.activity.project.ExamineAdvActivity;
import com.linkage.seapeak.pojo.UploadImage;
import com.linkage.seapeak.view.QuickPopView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.linkage.jz.bankruptcy.activity.Project.ZQUser.CreateZQFristApplyActivity.KEY_CREDITORID;
import static com.linkage.jz.bankruptcy.activity.Project.ZQUser.CreateZQFristApplyActivity.KEY_CREDITOR_RIGHTS_ID;
import static com.linkage.jz.bankruptcy.activity.Project.ZQUser.CreateZQFristApplyActivity.KEY_EDITING;
import static com.linkage.jz.bankruptcy.activity.Project.ZQUser.CreateZQFristApplyActivity.KEY_EDITING_FILE_LISTS;
import static com.linkage.jz.bankruptcy.activity.Project.ZQUser.CreateZQFristApplyActivity.KEY_TYPE;


/**
 * A login screen that offers login via email/password.
 */
public  class CreateZQFristApplyTwoActivity extends BaseCreateActivity implements OnClickListener, ZQApplyView{
    private static final String TAG = CreateZQFristApplyTwoActivity.class.getSimpleName();

    Button top_back;
    TextView top_mune1, top_mune2;
    private RadioGroup radioGroupArbitrate, radioGroupExecute;
    private RecyclerView uploadArbitrateRv, uploadExecuteRv, uploadOtherRv;
    private EditText editExecute;

    private static ZQBaseProjectCrDecInfo mEditInfo;
    private int mType;
    private String mCreditorId;
    private String mProjectId;
    private TempSavePresenter mTempSavePresenter;
    private String mCreditorRightsId;
    private SerializedZQApplyFileList mSerializedZQApplyFileLists;

    private TextView popClick;

    private final ObjValInfo onlineOVI = new ObjValInfo("1", "在线上传"),
            offlineOVI = new ObjValInfo("2", "线下提供"),
            noneOVI = new ObjValInfo("3", "无");

    private SelectPicHelpler<TaskAtta> mArbitrateSeletor,  mExecuteSeletor, mOtherSeletor;
    private final UploadImageConverter<TaskAtta> mConverter = new UploadImageConverter<TaskAtta>() {
        @Override
        public UploadImage toUploadImage(TaskAtta taskAtta) {
            UploadImage image = new UploadImage();
            image.setFilename(taskAtta.getAttachmentName());
            image.setFilesize(taskAtta.getAttachmentSize());
            image.setFilepath(taskAtta.getAttachmentDownloadAddress());
            image.setLoadUrl(taskAtta.getAttachmentThumbnailAddress());
            return image;
        }

        @Override
        public TaskAtta fromUploadImage(UploadImage image) {
            TaskAtta taskAtta = new TaskAtta();
            taskAtta.setAttachmentName(image.getFilename());
            taskAtta.setAttachmentSize(image.getFilesize());
            taskAtta.setAttachmentDownloadAddress(image.getFilepath());
            taskAtta.setAttachmentPreviewAddress(image.getLoadUrl());
            return null;
        }
    };

    /**
     *  @param context 上下文
     * @param creditorId 债权人ID
     * @param projectId 项目Id
     * @param editing //正在编辑的
     * @param type 0:管理人; 1:债权人
     */
    public static void start(Context context,
                             String creditorId, String projectId, int type, ZQBaseProjectCrDecInfo editing,
                             SerializedZQApplyFileList serializedZQApplyFileLists, String creditorRightsId,ZQBaseProjectCrDecInfo editInfo) {
        mEditInfo = editInfo;
        Intent intent = new Intent(context, CreateZQFristApplyTwoActivity.class);
        intent.putExtra(KEY_CREDITORID, creditorId);
        intent.putExtra(KEY_PROJECTID, projectId);
        intent.putExtra(KEY_TYPE, type);
        intent.putExtra(KEY_EDITING, editing);
        intent.putExtra(KEY_EDITING_FILE_LISTS, serializedZQApplyFileLists);
        intent.putExtra(KEY_CREDITOR_RIGHTS_ID, creditorRightsId);
        context.startActivity(intent);
    }

    @Override
    public void initData() {

    }

    @Override
    public void setListener() {
        top_back.setOnClickListener(this);
        top_mune1.setOnClickListener(this);
        top_mune2.setOnClickListener(this);
    }

    @Override
    public void initTitle() {
        ((TextView) findViewById(R.id.top_title)).setText("上传申报文件");
    }

    @Override
    public void initView() {
        top_back = findViewById(R.id.top_back);
        top_mune1 = findViewById(R.id.top_mune1);
        top_mune2 = findViewById(R.id.top_mune2);
        editExecute = findViewById(R.id.edit_execute);
        radioGroupArbitrate = findViewById(R.id.radio_group_arbitrate);
        radioGroupExecute = findViewById(R.id.radio_group_execute);
        uploadArbitrateRv = findViewById(R.id.upload_arbitrate);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        uploadArbitrateRv.setLayoutManager(manager);
        uploadExecuteRv = findViewById(R.id.upload_execute);
        FullyGridLayoutManager manager1 = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        uploadExecuteRv.setLayoutManager(manager1);
        uploadOtherRv = findViewById(R.id.upload_other);
        FullyGridLayoutManager manager2 = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        uploadOtherRv.setLayoutManager(manager2);

        popClick = findViewById(R.id.pop_click);
        /**
         * 弹窗
         */
        popClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QuickPopView.show(CreateZQFristApplyTwoActivity.this);
            }
        });

        radioGroupArbitrate.setOnCheckedChangeListener(
                (group, checkedId) -> {
                    uploadArbitrateRv.setVisibility(checkedId == R.id.arbitrate1 ? View.VISIBLE : View.GONE);
                    if (mEditInfo != null) {
                        switch (checkedId) {
                            case R.id.arbitrate1:
                                mEditInfo.setHasEffectiveJudgment(onlineOVI);
                                break;
                            case R.id.arbitrate2:
                                mEditInfo.setHasEffectiveJudgment(offlineOVI);
                                break;
                            case R.id.arbitrate3:
                                mEditInfo.setHasEffectiveJudgment(noneOVI);

                        }
                    }
                });
        radioGroupExecute.setOnCheckedChangeListener(
                (group, checkedId) -> {
                    uploadExecuteRv.setVisibility(checkedId == R.id.execute1 ? View.VISIBLE : View.GONE);
                    if (mEditInfo != null) {
                        switch (checkedId) {
                            case R.id.execute1:
                                mEditInfo.setHasApplyExecution(onlineOVI);
                                break;
                            case R.id.execute2:
                                mEditInfo.setHasApplyExecution(offlineOVI);
                                break;
                            case R.id.execute3:
                                mEditInfo.setHasApplyExecution(noneOVI);

                        }
                    }
                    editExecute.setVisibility(checkedId == R.id.execute1 ? View.VISIBLE : View.GONE);
                });
        if (mEditInfo != null) {

             List<UploadImage> mImgList1 = new ArrayList<>();
            if (mEditInfo.getJudgmentAtta() != null) {
                for (int i = 0; i < mEditInfo.getJudgmentAtta().size(); i++) {
                    TaskAtta atta = mEditInfo.getJudgmentAtta().get(i);
                    JSONObject obj = new JSONObject();
                    try {
                        obj.putOpt("filename", atta.getAttachmentName());
                        obj.putOpt("filepath", atta.getAttachmentDownloadAddress());
                        obj.putOpt("filesize", atta.getAttachmentSize());
                        obj.putOpt("loadUrl", atta.getAttachmentPreviewAddress());
                        mImgList1.add(new Gson().fromJson(obj.toString(), UploadImage.class));
                        BaseCreateActivity.sorFiles(mImgList1, true);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
            List<TaskAtta> mImgList11 = new ArrayList<>();
//            mArbitrateSeletor = new SelectPicHelpler<>(this, mImgList1, mConverter);
            mArbitrateSeletor = new SelectPicHelpler<>(this, mEditInfo.getJudgmentAtta(), mConverter);
            mArbitrateSeletor.initView(uploadArbitrateRv);
            if (mEditInfo.getHasEffectiveJudgment() != null) {
                switch (mEditInfo.getHasEffectiveJudgment().getValue()) {
                    case "1":
                        radioGroupArbitrate.check(R.id.arbitrate1);
                        break;
                    case "2":
                        radioGroupArbitrate.check(R.id.arbitrate2);
                        break;
                    case "3":
                        radioGroupArbitrate.check(R.id.arbitrate3);
                        break;
                }
            } else {
                ObjValInfo info = new ObjValInfo();
                info.setValue("3");
                mEditInfo.setHasEffectiveJudgment(info);
                radioGroupArbitrate.check(R.id.arbitrate3);
            }

//            List<UploadImage> mImgList2 = new ArrayList<>();
//            if (mEditInfo.getExecutionAtta() != null) {
//                for (int i = 0; i < mEditInfo.getExecutionAtta().size(); i++) {
//                    TaskAtta atta = mEditInfo.getExecutionAtta().get(i);
//                    JSONObject obj = new JSONObject();
//                    try {
//                        obj.putOpt("filename", atta.getAttachmentName());
//                        obj.putOpt("filepath", atta.getAttachmentDownloadAddress());
//                        obj.putOpt("filesize", atta.getAttachmentSize());
//                        obj.putOpt("loadUrl", atta.getAttachmentPreviewAddress());
//                        mImgList2.add(new Gson().fromJson(obj.toString(), UploadImage.class));
//                        BaseCreateActivity.sorFiles(mImgList2, true);
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//            mExecuteSeletor = new SelectPicHelpler(this,mImgList2, mConverter);
            mExecuteSeletor = new SelectPicHelpler(this,mEditInfo.getExecutionAtta(), mConverter);
            mExecuteSeletor.initView(uploadExecuteRv);
            if (mEditInfo.getHasApplyExecution() != null) {
                switch (mEditInfo.getHasApplyExecution().getValue()) {
                    case "1":
                        radioGroupExecute.check(R.id.execute1);
                        break;
                    case "2":
                        radioGroupExecute.check(R.id.execute2);
                        break;
                    case "3":
                        radioGroupExecute.check(R.id.execute3);
                        break;
                }
            } else {
                ObjValInfo info1 = new ObjValInfo();
                info1.setValue("3");
                mEditInfo.setHasApplyExecution(info1);
                radioGroupExecute.check(R.id.execute3);
            }

//            List<UploadImage> mImgList3 = new ArrayList<>();
//            if (mEditInfo.getOtherAtta() != null) {
//                for (int i = 0; i < mEditInfo.getOtherAtta().size(); i++) {
//                    TaskAtta atta = mEditInfo.getOtherAtta().get(i);
//                    JSONObject obj = new JSONObject();
//                    try {
//                        obj.putOpt("filename", atta.getAttachmentName());
//                        obj.putOpt("filepath", atta.getAttachmentDownloadAddress());
//                        obj.putOpt("filesize", atta.getAttachmentSize());
//                        obj.putOpt("loadUrl", atta.getAttachmentPreviewAddress());
//                        mImgList3.add(new Gson().fromJson(obj.toString(), UploadImage.class));
//                        BaseCreateActivity.sorFiles(mImgList3, true);
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//            mOtherSeletor = new SelectPicHelpler(this, mImgList3, mConverter);
            mOtherSeletor = new SelectPicHelpler(this, mEditInfo.getOtherAtta(), mConverter);
            if (mEditInfo.getExecutiveDetail() != null) editExecute.setText(mEditInfo.getExecutiveDetail());

            mOtherSeletor.initView(uploadOtherRv);
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_create_zq_frist_two_apply);
        mType = getIntent().getIntExtra(KEY_TYPE, 0);
        mCreditorId = getIntent().getStringExtra(KEY_CREDITORID);
        mProjectId = getIntent().getStringExtra(KEY_PROJECTID);
//        mEditInfo = getIntent().getParcelableExtra(KEY_EDITING);
        mSerializedZQApplyFileLists = getIntent().getParcelableExtra(KEY_EDITING_FILE_LISTS);
        mCreditorRightsId = getIntent().getStringExtra(KEY_CREDITOR_RIGHTS_ID);
        super.onCreate(savedInstanceState);
        mTempSavePresenter = new TempSavePresenter(this,
                mShapeLoadingDialog, mProjectId, mCreditorId, mType, mCreditorRightsId, mEditInfo, mSerializedZQApplyFileLists);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.top_back:
                onBackPressed();
                break;
            case R.id.top_mune1:
                if (checkAmountValidate()) {
                    syncEdit();
                    CreateZQFristApplyThreeActivity.start(this,
                            mCreditorId, mProjectId, mType, mEditInfo, mSerializedZQApplyFileLists, mCreditorRightsId);
                    finish();
                }
                break;
            case R.id.top_mune2:
                mTempSavePresenter.tempSave();
                break;
            default:
                break;
        }
    }

    @Override
    public void syncEdit() {
        mEditInfo.setExecutiveDetail(editExecute.getText().toString());
//        if (mArbitrateSeletor != null && mSerializedZQApplyFileLists != null) {

        try {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < mArbitrateSeletor.getUploadedImages().size(); i++) {
                if (TextUtils.equals(mArbitrateSeletor.getUploadedImages().get(i).getFilename(), NAME_ADD)) {
                    continue;
                }
                JSONObject jsonObject = new JSONObject();
                UploadImage image = mArbitrateSeletor.getUploadedImages().get(i);
//                jsonObject.put("attachmentName", urlList1.get(i).getFilename());
                jsonObject.putOpt("attachmentName", "相关附件" + (i + 1) + ".jpg");
                jsonObject.put("attachmentDownloadAddress", image.getFilepath());
                jsonObject.put("attachmentSize", image.getFilesize());
                jsonArray.put(jsonObject);
            }

            mSerializedZQApplyFileLists.setHasEffectiveJudgmentJson(jsonArray.toString());
//        }
//        if (mExecuteSeletor != null && mSerializedZQApplyFileLists != null) {

            JSONArray jsonArray2 = new JSONArray();
            for (int i = 0; i < mExecuteSeletor.getUploadedImages().size(); i++) {
                if (TextUtils.equals(mExecuteSeletor.getUploadedImages().get(i).getFilename(), NAME_ADD)) {
                    continue;
                }
                JSONObject jsonObject = new JSONObject();
                UploadImage image = mExecuteSeletor.getUploadedImages().get(i);
//                jsonObject.put("attachmentName", urlList1.get(i).getFilename());
                jsonObject.putOpt("attachmentName", "相关附件" + (i + 1) + ".jpg");
                jsonObject.put("attachmentDownloadAddress", image.getFilepath());
                jsonObject.put("attachmentSize", image.getFilesize());
                jsonArray2.put(jsonObject);
            }

            mSerializedZQApplyFileLists.setHasApplyExecutionJson(jsonArray2.toString());
//        }
//        if (mOtherSeletor != null && mSerializedZQApplyFileLists != null) {

            JSONArray jsonArray3 = new JSONArray();
            for (int i = 0; i < mOtherSeletor.getUploadedImages().size(); i++) {
                if (TextUtils.equals(mOtherSeletor.getUploadedImages().get(i).getFilename(), NAME_ADD)) {
                    continue;
                }
                JSONObject jsonObject = new JSONObject();
                UploadImage image = mOtherSeletor.getUploadedImages().get(i);
//                jsonObject.put("attachmentName", urlList1.get(i).getFilename());
                jsonObject.putOpt("attachmentName", "相关附件" + (i + 1) + ".jpg");
                jsonObject.put("attachmentDownloadAddress", image.getFilepath());
                jsonObject.put("attachmentSize", image.getFilesize());
                jsonArray3.put(jsonObject);
            }

            mSerializedZQApplyFileLists.setHasOtherDeclarationFileJson(jsonArray3.toString());
//        }
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    @Override
    public String getUserToken() {
        return super.getUserToken();
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void onBackPressed() {
        mTempSavePresenter.onBackPressed();
    }

    private boolean checkAmountValidate() {
        if (radioGroupArbitrate.getCheckedRadioButtonId() == R.id.arbitrate1
                && mArbitrateSeletor.getUploadedImages().size()==1) {
                new android.support.v7.app.AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("请上传生效判决/裁决，或选择其他选项")
                    .setCancelable(false)
                    .setPositiveButton("我知道了", null)
                    .show();
            return false;
        }
        if (radioGroupExecute.getCheckedRadioButtonId() == R.id.execute1
                && mExecuteSeletor.getUploadedImages().size()==1) {
            new android.support.v7.app.AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("请上传申请执行文件，或选择其他选项")
                    .setCancelable(false)
                    .setPositiveButton("我知道了", null)
                    .show();
            return false;
        }
        return true;
    }

}

